﻿using System;
using System.Collections.Generic;
using System.Linq;
using Hasiu.Entity;
using NHibernate;
using NHibernate.Linq;
using NHibernate.Criterion;

namespace Hasiu.Service
{
    public class ProductImgService
    {
        public static readonly ProductImgService _ = new ProductImgService();

        private ISession Session { get; set; }

        public ProductImgService()
        {
            Session = NHibernateHelper.GetCurrentSession();
        }

        public void Save(ProductImg productImg)
        {
            Session.Clear();
            Session.Save(productImg);
            Session.Flush();
        }

        public void Update(ProductImg productImg)
        {
            Session.Clear();
            Session.Update(productImg);
            Session.Flush();
        }

        public void Delete(params string[] id)
        {
            Session.Clear();
            var query = Session.Query<ProductImg>().Where(o => id.Contains(o.Id));
            foreach (var v in query)
            {
                Session.Delete(v);
            }
            Session.Flush();
        }

        public ProductImg Get(string id)
        {
            return Session.Get<ProductImg>(id);
        }

        public IList<ProductImg> GetList(string productId)
        {
            return Session.Query<ProductImg>().Where(o => o.ProductId == productId).ToList();
        }

        public int GetCount(string productId)
        {
            return Convert.ToInt32(Session.CreateCriteria(typeof(ProductImg))
                .Add(Restrictions.Eq("ProductId", productId))
                .SetProjection(Projections.Count("Id"))
                .UniqueResult());
        }
    }
}
